import React, { useState, useEffect } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { Card, Button, Space, Spin, message } from 'antd';
import { ArrowLeftOutlined } from '@ant-design/icons';
import { contestService } from '@/services/contestService';
import { Contest } from '@/types/contest';
import styles from './Edit.module.css';
import ContestForm from './components/ContestForm';

const ContestEdit: React.FC = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const [contest, setContest] = useState<Contest | null>(null);
  const [initializing, setInitializing] = useState(true);

  useEffect(() => {
    const fetchContest = async () => {
      try {
        setInitializing(true);
        const response = await contestService.getContest(Number(id));
        setContest(response.data.data);
      } catch (error) {
        message.error('获取比赛信息失败');
        navigate('/admin/contest/list');
      } finally {
        setInitializing(false);
      }
    };

    if (id) {
      fetchContest();
    }
  }, [id, navigate]);

  const handleSubmit = async (values: any) => {
    if (!id) return;
    
    try {
      setLoading(true);
      await contestService.updateContest(Number(id), values);
      message.success('更新成功');
      navigate('/admin/contest/list');
    } catch (error) {
      message.error('更新失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCancel = () => {
    navigate('/admin/contest/list');
  };

  if (initializing) {
    return (
      <div className={styles.loadingContainer}>
        <Spin size="large" />
      </div>
    );
  }

  return (
    <div className={styles.container}>
      <Card>
        <div className={styles.header}>
          <h2>编辑比赛</h2>
          <Button 
            icon={<ArrowLeftOutlined />} 
            onClick={() => navigate('/admin/contest/list')}
          >
            返回列表
          </Button>
        </div>
        
        <ContestForm 
          initialValues={contest || undefined}
          onFinish={handleSubmit}
          onCancel={handleCancel}
          loading={loading}
          submitText="保存"
          cancelText="取消"
        />
      </Card>
    </div>
  );
};

export default ContestEdit; 